package com.gitee.cui.websocket;

import com.gitee.cui.util.Dateutil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * websocket文本处理器
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/1 15:20
 **/
@Slf4j
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
        // 判断请求数据是不是文本数据
        if (msg instanceof TextWebSocketFrame) {
            // 获取请求的内容
            String text = ((TextWebSocketFrame) msg).text();
            log.debug("服务端收到请求：" + text);
            // 组装回复请求
            String response = Dateutil.getTime() + ":" + text;
            TextWebSocketFrame frame = new TextWebSocketFrame(response);
            ctx.writeAndFlush(frame);
        } else {
            log.debug("本测试程序仅支持文本消息，不支持二进制消息");
            String message = "unsupported frame type: " + msg.getClass().getName();
            throw new UnsupportedOperationException(message);
        }
    }
}
